package cn.walls1717.ggkt.live.service.impl;

import cn.walls1717.ggkt.client.course.CourseFeignClient;
import cn.walls1717.ggkt.client.user.UserInfoFeignClient;
import cn.walls1717.ggkt.exception.MyException;
import cn.walls1717.ggkt.live.mapper.LiveCourseMapper;
import cn.walls1717.ggkt.live.mtcloud.CommonResult;
import cn.walls1717.ggkt.live.mtcloud.MTCloud;
import cn.walls1717.ggkt.live.service.*;
import cn.walls1717.ggkt.model.live.*;
import cn.walls1717.ggkt.model.user.UserInfo;
import cn.walls1717.ggkt.model.vod.Teacher;
import cn.walls1717.ggkt.util.DateUtil;
import cn.walls1717.ggkt.vo.live.LiveCourseConfigVo;
import cn.walls1717.ggkt.vo.live.LiveCourseFormVo;
import cn.walls1717.ggkt.vo.live.LiveCourseGoodsView;
import cn.walls1717.ggkt.vo.live.LiveCourseVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 直播课程表服务实现类
 *
 * @author walls1717
 * @since 2022/07/23
 */
@Slf4j
@Service
public class LiveCourseServiceImpl extends ServiceImpl<LiveCourseMapper, LiveCourse> implements LiveCourseService {

    @Autowired
    private CourseFeignClient teacherFeignClient;

    @Resource
    private MTCloud mtCloudClient;

    @Resource
    private LiveCourseAccountService liveCourseAccountService;

    @Resource
    private LiveCourseDescriptionService liveCourseDescriptionService;

    @Autowired
    private LiveCourseGoodsService liveCourseGoodsService;

    @Autowired
    private LiveCourseConfigService liveCourseConfigService;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    /**
     * 直播课程分页展示
     */
    @Override
    public Page<LiveCourse> listPages(Long pageNum, Long pageSize) {
        Page<LiveCourse> liveCoursePage = new Page<>(pageNum, pageSize);
        this.page(liveCoursePage);
        List<LiveCourse> records = liveCoursePage.getRecords();
        records.forEach(item -> {
            Long teacherId = item.getTeacherId();
            Teacher teacherInfo = teacherFeignClient.innerGetTeacherById(teacherId);
            if (teacherInfo != null) {
                item.getParam().put("teacherName", teacherInfo.getName());
                item.getParam().put("teacherLevel", teacherInfo.getLevel());
            }
        });
        return liveCoursePage;
    }

    /**
     * 添加直播课程
     */
    @Override
    public void saveLiveCourse(LiveCourseFormVo liveCourseFormVo) {
        LiveCourse liveCourse = new LiveCourse();
        BeanUtils.copyProperties(liveCourseFormVo, liveCourse);

        Teacher teacher = teacherFeignClient.innerGetTeacherById(liveCourseFormVo.getTeacherId());
        HashMap<Object, Object> options = new HashMap<>();
        // 直播类型。1: 教育直播，2: 生活直播。默认 1，说明：根据平台开通的直播类型填写
        options.put("scenes", 2);
        options.put("password", liveCourseFormVo.getPassword());
        try {
            String res = mtCloudClient.courseAdd(liveCourse.getCourseName(),
                    teacher.getId().toString(),
                    new DateTime(liveCourse.getStartTime()).toString("yyyy-MM-dd HH:mm:ss"),
                    new DateTime(liveCourse.getEndTime()).toString("yyyy-MM-dd HH:mm:ss"),
                    teacher.getName(),
                    teacher.getIntro(),
                    options);
            log.info("res : {}", res);
            CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
            if (Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {
                JSONObject object = commonResult.getData();
                liveCourse.setCourseId(object.getLong("course_id"));
                this.save(liveCourse);
                //保存课程详情信息
                LiveCourseDescription liveCourseDescription = new LiveCourseDescription();
                liveCourseDescription.setDescription(liveCourseFormVo.getDescription());
                liveCourseDescription.setLiveCourseId(liveCourse.getId());
                liveCourseDescriptionService.save(liveCourseDescription);

                //保存课程账号信息
                LiveCourseAccount liveCourseAccount = new LiveCourseAccount();
                liveCourseAccount.setLiveCourseId(liveCourse.getId());
                liveCourseAccount.setZhuboAccount(object.getString("bid"));
                liveCourseAccount.setZhuboPassword(liveCourseFormVo.getPassword());
                liveCourseAccount.setAdminKey(object.getString("admin_key"));
                liveCourseAccount.setUserKey(object.getString("user_key"));
                liveCourseAccount.setZhuboKey(object.getString("zhubo_key"));
                liveCourseAccountService.save(liveCourseAccount);
            } else {
                log.info(commonResult.getmsg());
                throw new MyException(20001, "直播创建失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除直播课程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteLiveCourseById(Long id) {
        LiveCourse liveCourse = this.getById(id);
        if (liveCourse != null) {
            Long courseId = liveCourse.getCourseId();
            try {
                // 删除直播平台课程
                mtCloudClient.courseDelete(courseId.toString());
                // 删除数据库
                this.removeById(id);
            } catch (Exception e) {
                throw new MyException(20001, "删除直播课程失败");
            }
        }
    }

    /**
     * 根据id获取LiveCourseFormVo
     */
    @Override
    public LiveCourseFormVo getLiveCourseFormById(Long id) {
        LiveCourse liveCourse = this.getById(id);
        LiveCourseDescription liveCourseDescription = liveCourseDescriptionService.getLiveCourse(id);
        LiveCourseFormVo liveCourseFormVo = new LiveCourseFormVo();
        BeanUtils.copyProperties(liveCourse, liveCourseFormVo);
        liveCourseFormVo.setDescription(liveCourseDescription.getDescription());
        return liveCourseFormVo;
    }

    /**
     * 修改
     */
    @Override
    public void updateLiveCourse(LiveCourseFormVo liveCourseFormVo) {
        // 获取直播课程信息
        LiveCourse liveCourse = this.getById(liveCourseFormVo.getId());
        BeanUtils.copyProperties(liveCourseFormVo, liveCourse);
        // 获取讲师信息
        Teacher teacher = teacherFeignClient.innerGetTeacherById(liveCourseFormVo.getTeacherId());
        HashMap<Object, Object> options = new HashMap<>();
        try {
            String res = mtCloudClient.courseUpdate(
                    liveCourse.getCourseId().toString(),
                    teacher.getId().toString(),
                    liveCourse.getCourseName(),
                    new DateTime(liveCourse.getStartTime()).toString("yyyy-MM-dd HH:mm:ss"),
                    new DateTime(liveCourse.getEndTime()).toString("yyyy-MM-dd HH:mm:ss"),
                    teacher.getName(),
                    teacher.getIntro(),
                    options
            );
            // 返回结果转换，判断是否成功
            CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
            if (Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {
                JSONObject object = commonResult.getData();
                // 更新直播课程基本信息
                liveCourse.setCourseId(object.getLong("course_id"));
                baseMapper.updateById(liveCourse);
                // 直播课程描述信息更新
                LiveCourseDescription liveCourseDescription = liveCourseDescriptionService.getLiveCourse(liveCourse.getId());
                liveCourseDescription.setDescription(liveCourseFormVo.getDescription());
                liveCourseDescriptionService.updateById(liveCourseDescription);
            } else {
                throw new MyException(20001, "修改直播课程失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取配置信息
     */
    @Override
    public LiveCourseConfigVo getCourseConfigById(Long id) {
        LiveCourseConfig liveCourseConfig = liveCourseConfigService.getCourseConfigByCourseId(id);
        LiveCourseConfigVo liveCourseConfigVo = new LiveCourseConfigVo();
        if (liveCourseConfig != null) {
            // 查询直播课程商品列表
            List<LiveCourseGoods> courseGoods = liveCourseGoodsService.getByCourseId(id);
            BeanUtils.copyProperties(liveCourseConfig, liveCourseConfigVo);
            liveCourseConfigVo.setLiveCourseGoodsList(courseGoods);
        }
        return liveCourseConfigVo;
    }

    /**
     * 修改配置信息
     */
    @Override
    public void updateLiveConfig(LiveCourseConfigVo liveCourseConfigVo) {
        // 修改直播配置表
        LiveCourseConfig liveCourseConfig = new LiveCourseConfig();
        BeanUtils.copyProperties(liveCourseConfigVo, liveCourseConfig);
        if (liveCourseConfigVo.getId() == null) {
            liveCourseConfigService.save(liveCourseConfig);
        } else {
            liveCourseConfigService.updateById(liveCourseConfig);
        }

        // 修改直播商品表
        LambdaQueryWrapper<LiveCourseGoods> lqw = new LambdaQueryWrapper<>();
        lqw.eq(LiveCourseGoods::getLiveCourseId, liveCourseConfigVo.getLiveCourseId());
        // 先删除再添加
        liveCourseGoodsService.remove(lqw);
        List<LiveCourseGoods> liveCourseGoodsList = liveCourseConfigVo.getLiveCourseGoodsList();
        if (!CollectionUtils.isEmpty(liveCourseGoodsList)) {
            liveCourseGoodsService.saveBatch(liveCourseGoodsList);
        }

        // 修改直播平台信息
        this.updateLifeConfig(liveCourseConfigVo);
    }

    /**
     * 修改直播平台信息
     */
    private void updateLifeConfig(LiveCourseConfigVo liveCourseConfigVo) {
        LiveCourse liveCourse = this.getById(liveCourseConfigVo.getLiveCourseId());
        //参数设置
        HashMap<Object, Object> options = new HashMap<>(5);
        //界面模式
        options.put("pageViewMode", liveCourseConfigVo.getPageViewMode());
        //观看人数开关
        JSONObject number = new JSONObject();
        number.put("enable", liveCourseConfigVo.getNumberEnable());
        options.put("number", number.toJSONString());
        //观看人数开关
        JSONObject store = new JSONObject();
        store.put("enable", liveCourseConfigVo.getStoreEnable());
        store.put("type", liveCourseConfigVo.getStoreType());
        options.put("store", store.toJSONString());
        //商城列表
        List<LiveCourseGoods> liveCourseGoodsList = liveCourseConfigVo.getLiveCourseGoodsList();
        if (!CollectionUtils.isEmpty(liveCourseGoodsList)) {
            List<LiveCourseGoodsView> liveCourseGoodsViewList = new ArrayList<>();
            for (LiveCourseGoods liveCourseGoods : liveCourseGoodsList) {
                LiveCourseGoodsView liveCourseGoodsView = new LiveCourseGoodsView();
                BeanUtils.copyProperties(liveCourseGoods, liveCourseGoodsView);
                liveCourseGoodsViewList.add(liveCourseGoodsView);
            }
            JSONObject goodsListEdit = new JSONObject();
            goodsListEdit.put("status", "0");
            options.put("goodsListEdit ", goodsListEdit.toJSONString());
            options.put("goodsList", JSON.toJSONString(liveCourseGoodsViewList));
        }

        String res = null;
        try {
            res = mtCloudClient.courseUpdateLifeConfig(liveCourse.getCourseId().toString(), options);
            CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
            if (Integer.parseInt(commonResult.getCode()) != MTCloud.CODE_SUCCESS) {
                throw new MyException(20001, "修改配置信息失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取最近的直播
     */
    @Override
    public List<LiveCourseVo> listLatelyLives() {
        List<LiveCourseVo> liveCourseVoList = baseMapper.getLatelyList();
        liveCourseVoList.forEach(item -> {
            // 封装开始和结束时间
            item.setStartTimeString(new DateTime(item.getStartTime()).toString("yyyy年MM月dd HH:mm"));
            item.setEndTimeString(new DateTime(item.getEndTime()).toString("HH:mm"));

            // 封装讲师
            Long teacherId = item.getTeacherId();
            Teacher teacher = teacherFeignClient.innerGetTeacherById(teacherId);
            item.setTeacher(teacher);

            item.setLiveStatus(this.getLiveStatus(item));
        });
        return liveCourseVoList;
    }

    /**
     * 获取用户access_token
     */
    @Override
    public JSONObject getPlayAuth(Long id, Long userId) {
        // 获取直播课程信息
        LiveCourse liveCourse = this.getById(id);
        // 获取用户信息
        UserInfo userInfo = userInfoFeignClient.innerGetUserById(userId);

        HashMap<Object, Object> options = new HashMap<>();
        String res = null;
        try {
            res = mtCloudClient.courseAccess(liveCourse.getCourseId().toString(),
                    userId.toString(),
                    userInfo.getNickName(),
                    MTCloud.ROLE_USER,
                    80 * 80 * 80,
                    options);
            CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
            if (Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {
                JSONObject object = commonResult.getData();
                System.out.println("access::" + object.getString("access_token"));
                return object;
            } else {
                throw new MyException(20001, "获取失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据ID查询课程
     */
    @Override
    public Map<String, Object> getLiveCourseInfoByCourseId(Long courseId) {
        LiveCourse liveCourse = this.getById(courseId);
        liveCourse.getParam().put("startTimeString", new DateTime(liveCourse.getStartTime()).toString("yyyy年MM月dd HH:mm"));
        liveCourse.getParam().put("endTimeString", new DateTime(liveCourse.getEndTime()).toString("yyyy年MM月dd HH:mm"));
        Teacher teacher = teacherFeignClient.innerGetTeacherById(liveCourse.getTeacherId());
        LiveCourseDescription liveCourseDescription = liveCourseDescriptionService.getLiveCourse(courseId);

        Map<String, Object> map = new HashMap<>();
        map.put("liveCourse", liveCourse);
        map.put("liveStatus", this.getLiveStatus(liveCourse));
        map.put("teacher", teacher);
        if (null != liveCourseDescription) {
            map.put("description", liveCourseDescription.getDescription());
        } else {
            map.put("description", "");
        }
        return map;
    }

    /**
     * 直播状态 0：未开始 1：直播中 2：直播结束
     */
    private int getLiveStatus(LiveCourse liveCourse) {
        int liveStatus = 0;
        Date curTime = new Date();
        if (DateUtil.dateCompare(curTime, liveCourse.getStartTime())) {
            liveStatus = 0;
        } else if (DateUtil.dateCompare(curTime, liveCourse.getEndTime())) {
            liveStatus = 1;
        } else {
            liveStatus = 2;
        }
        return liveStatus;
    }
}
